package com.loan.common.pay.oddpay;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class HttpClientUtil {
    private static final Logger log = LoggerFactory.getLogger("businessLogger");
    public static String md5Key = "8BB418FCA8A480BC3E00365AE14148A2";
    public static String PAY_URL = "https://pay.vnoddpay.com:8090/pay-adapter/services/va/reg";

    public static void main(String[] args) {
        //notify2Merchant();
    }

    public static void notify2Merchant() {
        String url = "http://121.196.37.232:8081/repaymentOrder/oddPayVcCallback";
        HashMap<String, String> map1 = new HashMap<String, String>();
        map1.put("receiveTime", "20200703121009");
        map1.put("amount", "206000");
        map1.put("signInfo", "c83399c8782621aac5c6a694bbeae09c");
        map1.put("orderId", "ENJOYING2020070311101000783200703111607");
        map1.put("retInfo", "902002959331___ENJOY NGUYEN THI NHU HAU___m2006160001200703110234KTeQx21");
        map1.put("retCode", "0000");
        map1.put("merchId", "m2006160001");
        map1.put("txnId", "mg200703111009qu09vUU");
        map1.put("status", "02");
        Map<String, Object> resmap1 = httpSendPost(url, map1);
        System.out.println("==333=>" + net.sf.json.JSONObject.fromObject(resmap1));
    }

    @SuppressWarnings("rawtypes")
    public static Map<String, Object> httpSendGet(String url, HashMap<String, String> map) {
        log.debug("httpSendGet url is ====" + url);
        Map<String, Object> resmap = new HashMap<String, Object>();
        HttpClient httpClient = new HttpClient();
        //httpClient.getHostConfiguration().setProxy("127.0.0.1", 8080);
        GetMethod getMethod = new GetMethod(url);
        HttpMethodParams params = new HttpMethodParams();
        params.setContentCharset("UTF-8");
        getMethod.setParams(params);
        NameValuePair[] postData = new NameValuePair[map.size()];
        Iterator iter = map.keySet().iterator();
        int index = 0;
        while (iter.hasNext()) {
            Object key = iter.next();
            Object val = map.get(key);
            postData[index++] = new NameValuePair((String) key, (String) val);
        }
        getMethod.setQueryString(postData);
        try {
            int statusCode = httpClient.executeMethod(getMethod);//发送请求
            log.debug("the return code is ====" + statusCode);
            if (statusCode != HttpStatus.SC_OK) {
                log.debug("error code *************" + statusCode);
            } else {
                String responseBody = getMethod.getResponseBodyAsString();
                log.debug("httpRec***************" + responseBody);
                //System.out.println("httpRec***************"+responseBody);
                resmap = JsonTools.parseJSON2Map(responseBody);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.debug("httpSendGet异常：" + e.getMessage());
        } finally {
            if (getMethod != null) {
                getMethod.releaseConnection();//关闭连接
            }
        }
        return resmap;
    }

    @SuppressWarnings("rawtypes")
    public static String httpGet(String url, HashMap<String, String> map) {
        String res = "";
        HttpClient httpClient = new HttpClient();
        //httpClient.getHostConfiguration().setProxy("127.0.0.1", 8080);
        GetMethod getMethod = new GetMethod(url);
        HttpMethodParams params = new HttpMethodParams();
        params.setContentCharset("UTF-8");
        getMethod.setParams(params);
        NameValuePair[] postData = new NameValuePair[map.size()];
        Iterator iter = map.keySet().iterator();
        int index = 0;
        while (iter.hasNext()) {
            Object key = iter.next();
            Object val = map.get(key);
            postData[index++] = new NameValuePair((String) key, (String) val);
        }
        getMethod.setQueryString(postData);
        try {
            int statusCode = httpClient.executeMethod(getMethod);//发送请求
            if (statusCode != 200) {
                res = "error";
                log.info("服务端未正常响应，响应码：" + statusCode);
            } else {
                res = getMethod.getResponseBodyAsString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.debug("httpSendGet异常：" + e.getMessage());
            res = "error";
        } finally {
            if (getMethod != null) {
                getMethod.releaseConnection();//关闭连接
            }
        }
        return res;
    }

    @SuppressWarnings("rawtypes")
    public static byte[] httpSendByte(String url, HashMap<String, String> map) {
        byte[] res = null;
        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(url);
        HttpMethodParams params = new HttpMethodParams();
        params.setContentCharset("UTF-8");
        getMethod.setParams(params);
        NameValuePair[] postData = new NameValuePair[map.size()];
        Iterator iter = map.keySet().iterator();
        int index = 0;
        while (iter.hasNext()) {
            Object key = iter.next();
            Object val = map.get(key);
            postData[index++] = new NameValuePair((String) key, (String) val);
        }
        getMethod.setQueryString(postData);
        try {
            int statusCode = httpClient.executeMethod(getMethod);//发送请求
            if (statusCode != HttpStatus.SC_OK) {
                log.debug("error code *************" + statusCode);
            } else {
                res = getMethod.getResponseBody();
                log.debug("httpRec***************" + res.length);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.debug("httpSendByte异常：" + e.getMessage());
        } finally {
            if (getMethod != null) {
                getMethod.releaseConnection();//关闭连接
            }
        }
        return res;
    }

    @SuppressWarnings("rawtypes")
    public static String httpSendJson(String url, HashMap<String, String> map) {
        String res = "";
        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(url);
        HttpMethodParams params = new HttpMethodParams();
        params.setContentCharset("UTF-8");
        getMethod.addRequestHeader("Content-Type", "application/json");
        getMethod.setParams(params);
        NameValuePair[] postData = new NameValuePair[map.size()];
        Iterator iter = map.keySet().iterator();
        int index = 0;
        while (iter.hasNext()) {
            Object key = iter.next();
            Object val = map.get(key);
            postData[index++] = new NameValuePair((String) key, (String) val);
        }
        getMethod.setQueryString(postData);
        try {
            int statusCode = httpClient.executeMethod(getMethod);//发送请求
            if (statusCode != HttpStatus.SC_OK) {
                log.debug("error code *************" + statusCode);
            } else {
                res = getMethod.getResponseBodyAsString();
                log.debug("httpRec***************" + getMethod.getResponseBody().length);
                log.debug("httpRec***************" + res);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.debug("httpSendJson异常：" + e.getMessage());
        } finally {
            if (getMethod != null) {
                getMethod.releaseConnection();//关闭连接
            }
        }
        return res;
    }

    public static PostMethod init(String url) {
        PostMethod postMethod = new PostMethod(url);//POST请求
        postMethod.setRequestHeader("Host", "127.0.0.1");
        postMethod.setRequestHeader("Accept", "application/json,text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        postMethod.setRequestHeader("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
        postMethod.setRequestHeader("Accept-Encoding", "gzip, deflate");
        postMethod.setRequestHeader("Connection", "keep-alive");
        postMethod.setRequestHeader("Referer", "127.0.0.1");
        postMethod.setRequestHeader("Cache-Control", "no-cache");
        postMethod.setRequestHeader("Pragma", "no-cache");
        //postMethod.setRequestHeader("Content-Type", "application/json");
        HttpMethodParams params = new HttpMethodParams();
        params.setContentCharset("UTF-8");
        postMethod.setParams(params);
        return postMethod;
    }

    @SuppressWarnings("rawtypes")
    public static Map<String, Object> httpSendPost(String url, HashMap<String, String> map) {
        Map<String, Object> resmap = new HashMap<String, Object>();
        HttpClient httpClient = new HttpClient();
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30 * 1000);
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(90 * 1000);
        PostMethod postMethod = init(url);
        NameValuePair[] postData = new NameValuePair[map.size()];
        Iterator iter = map.keySet().iterator();
        int index = 0;
        while (iter.hasNext()) {
            Object key = iter.next();
            Object val = map.get(key);
            postData[index++] = new NameValuePair((String) key, (String) val);
        }
        postMethod.addParameters(postData);
        try {
            int statusCode = httpClient.executeMethod(postMethod);//发送请求
            if (statusCode != HttpStatus.SC_OK) {
                log.debug("error code *************" + statusCode);
            } else {
                String responseBody = postMethod.getResponseBodyAsString();
                if (responseBody != null && responseBody.length() > 300) {
                    log.debug("httpRec***************" + responseBody);
                }

                resmap = JsonTools.parseJSON2Map(responseBody);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.debug("httpSendPost异常：" + e.getMessage());
        } finally {
            if (postMethod != null) {
                postMethod.releaseConnection();//关闭连接
            }
        }
        return resmap;
    }

    @SuppressWarnings("rawtypes")
    public static String httpSendPosttoString(String url, HashMap<String, String> map) {
        String responseBody = "";
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = init(url);
        NameValuePair[] postData = new NameValuePair[map.size()];
        Iterator iter = map.keySet().iterator();
        int index = 0;
        while (iter.hasNext()) {
            Object key = iter.next();
            Object val = map.get(key);
            postData[index++] = new NameValuePair((String) key, (String) val);
        }
        postMethod.addParameters(postData);
        try {
            int statusCode = httpClient.executeMethod(postMethod);//发送请求
            if (statusCode != HttpStatus.SC_OK) {
                log.debug("error code *************" + statusCode);
            } else {
                responseBody = postMethod.getResponseBodyAsString();

                // if(responseBody != null && responseBody.length()>300){
                log.debug("httpRec***************" + responseBody);
                //System.out.println("===>"+responseBody+"<===");
                //responseBody = "{\"errorMsg\":\"该用户不属于此商户\"}";
                // }

            }
        } catch (Exception e) {
            e.printStackTrace();
            log.debug("httpSendPost异常：" + e.getMessage());
        } finally {
            if (postMethod != null) {
                postMethod.releaseConnection();//关闭连接
            }
        }
        return responseBody;
    }


}
